package org.huatek.anders.service;

import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author anders
 * @since 2018/11/15 20:23
 * HeadersExchange 交互器
 * 添加一个creditBank()方法，发送消息至creditBankExchange交换机且routingKey为credit.bank
 * 添加一个creditFinance()方法，发送消息至creditFinanceExchange交换机且routingKey为credit.finance
 */
@Component
@Service
@Slf4j
public class ApiCreditSenderServiceImpl implements ApiCreditSenderService {
    private final RabbitTemplate rabbitTemplate;
    @Autowired
    public ApiCreditSenderServiceImpl(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void creditBank(Map<String, Object> head, String msg){
        log.info("credit.bank send message: "+msg);
        rabbitTemplate.convertAndSend("creditBankExchange", "credit.bank", getMessage(head, msg));
    }

    @Override
    public void creditFinance(Map<String, Object> head, String msg){
        log.info("credit.finance send message: "+msg);
        rabbitTemplate.convertAndSend("creditFinanceExchange", "credit.finance", getMessage(head, msg));
    }

    private Message getMessage(Map<String, Object> head, Object msg){
        MessageProperties messageProperties = new MessageProperties();
        for (Map.Entry<String, Object> entry : head.entrySet()) {
            messageProperties.setHeader(entry.getKey(), entry.getValue());
        }
        MessageConverter messageConverter = new SimpleMessageConverter();
        return messageConverter.toMessage(msg, messageProperties);
    }
}
